package com.gougou.manager.web.controller.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gougou.manager.pojo.ItemCatResult;
import com.gougou.manager.service.impl.TbItemCatServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * 用于首页访问商品分类需要的Json格式数据且生成树状结构
 */
@RequestMapping("/ItemCatAPI")
@Controller
public class ApiItemCatController {

    @Autowired
    private TbItemCatServiceImpl tbItemCatService;

    //得到json字符串
    private static final ObjectMapper MAPPER=new ObjectMapper();


    /**
     * 对外提供接口服务查询所有类目数据
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<String> queryItemCatList(@RequestParam(value = "callback",required = false) String callback){
       try{
           ItemCatResult itemCatResult = this.tbItemCatService.queryAllTree();

           String json=MAPPER.writeValueAsString(itemCatResult);
          //判断是否为空
           if(StringUtils.isEmpty(callback)){
               return ResponseEntity.ok(json);
           }
           //如果不为空就通过jsonp返回callback拼接的json字符串，解决浏览器跨域问题
           return ResponseEntity.ok(callback+"("+json+")");

       }catch (Exception e){
          e.printStackTrace();
       }
       return ResponseEntity.status(HttpStatus.INSUFFICIENT_STORAGE).body(null);
    }
}
